1

I want to append some string after each line of the file except the header and footer of the files . So I have used below command to change the range of the lines except header and footer but its deleting header and footer and I do not want to delete the header and footer lines .

sed -n '2,5p; '"$str_var"'' abc.dat > abc.dat.temp

even I have tried to skip the header and modified other lines by using below command but no options for footer/ trailer line to keep it as unchange .

sed '1! s/$/'"$str_var"'/g' abc.dat > abc.dat.temp

any suggestions how to change all the lines of the file except the header and footer line and the command should not be deleting the header/footer line .

0

With awk, for a file of any number of lines:

$ awk -v last=$(wc -l < input) 'NR!=1 && NR!=last { print $0 " and more stuff" } NR==1||NR==last { print }' input
header
foo and more stuff
bar and more stuff
baz and more stuff
quux and more stuff
freeble and more stuff
bletch and more stuff
footer

Get the number of lines in the input file with wc, stash that in an awk variable. Then print the header and footer by themselves, and all other lines with the suffix:

NR!=1 && NR!=last {
   print $0 " and more stuff"
} 
NR==1 || NR==last {
    print
}
  • If you redirect the file, you don't need to filter: -v last="$(wc -l < input)" – glenn jackman Jun 5 '18 at 17:34
  • A cat with many skins, POSIX be. – DopeGhoti Jun 5 '18 at 18:02
6

Assuming the header and footer are one line each: for the first line and the last line, skip further processing. Each line is printed by default.

$ seq 10 | sed '1n; $n; s/$/ hello/'
1
2 hello
3 hello
4 hello
5 hello
6 hello
7 hello
8 hello
9 hello
10
1

With sed and in different way append to all lines s/$/.../ except ! the first 1 and will quit if it was the last line $ in advance.

sed '$q ;1 !s/$/ append/' <(seq 10)
1
2 append
3 append
4 append
5 append
6 append
7 append
8 append
9 append
10

Or using awk:

awk 'BEGIN{ getline line} {print line; line=$0 " append";} END{print $0}' <(seq 10)
1
2 append
3 append
4 append
5 append
6 append
7 append
8 append
9 append
10
0

Thank you all for the suggestions . It was really useful . I have written below command to do the same .

str_var=$(awk -F'\|\^' '{print $3}' abc.dat | head -1)

awk -v last=$(wc -l < inputFile) -v l="$str_var" '{if(NR==1){print $0} else if(NR==last){print $0} else{print $0 l}}' inputFile > outputFile

0

I have done by below method

inputfile

10
20
30
40

command

 for i in `awk '{print NR}' inputfile| wc -l| awk '{print $1-1}'`; do sed '2,'$i's/$/praveen/g' inputfile;done

output

10
20praveen
30praveen
40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.