tags:

views:

77

answers:

3

Hi,

given a plain text file, how can I do, using bash, awk, sed, etc, to, at the line number NLINE, add the string STR, just n spaces after the end of the line?

So, for instance, if this is the line NLINE:

date march 13th

for 5 spaces, we get

date march 13th     STR

and one gets the modification in a new file.

Thanks

+2  A: 
$ NLINE=666
$ APPEND="    xxx"
$ sed "${NLINE}s/\$/${APPEND}/" FILENAME

Just be careful that APPEND does not contain any characters sed might interpret.

ndim
A: 
#!/bin/bash
NLINE=10
n=5
string="STR"
while read -r line
do
    if (( ++count == NLINE ))
    then
        printf "%s%${n}s%2\n" "$line" " " "$string"
    else
        echo "$line"
    fi
done < inputfile > outputfile
Dennis Williamson
+1  A: 
NLINE=2
s="somestring"
sp="     "
awk -vn="$NLINE" -vs="$s" -vsp="$sp" 'NR==n{$0=$0 sp s}1' file >temp
mv temp file
ghostdog74
+1 for properly handling double quotes inside `s`. You can of course also use `sprintf("%" nsp "s", "")` to programatically synthesize `sp` from a *number* of spaces `nsp` as the OP inferred, although I agree it is overkill if the OP knows upfront how many spaces.
vladr