knowledgeseeker
knowledgeseeker

Reputation: 359

How to append a string to a file from the nth line onwards in shell script?

I want to add a string to the file at the end of each line starting from the second line .

so this is my file budget.txt

id,budget
d4385ff7-247f-407a-97c6-366d8128c6c7,
50548d0a-257c-44f5-b175-2e7efa53dc35,
e15965cf-ffc1-40ae-94c4-b450ab190233,
b9286b97-2575-4c98-bd24-1393d5309e76,

the output i am expecting is below. I want to add the string 'True' starting from the second line onwards in the end.

id,budget
d4385ff7-247f-407a-97c6-366d8128c6c7,True
50548d0a-257c-44f5-b175-2e7efa53dc35,True
e15965cf-ffc1-40ae-94c4-b450ab190233,True
b9286b97-2575-4c98-bd24-1393d5309e76,True

what could be the shortest bash command . thank you so much appreciate any help

Upvotes: 0

Views: 719

Answers (1)

P....
P....

Reputation: 18411

Make sure to run dos2unix budget.txt on your file before running the commands below, in general .txt files are originated on windows so have different line ending.

awk 'NR>1{$0=$0"True"}1' file
id,budget
d4385ff7-247f-407a-97c6-366d8128c6c7,True
50548d0a-257c-44f5-b175-2e7efa53dc35,True
e15965cf-ffc1-40ae-94c4-b450ab190233,True
b9286b97-2575-4c98-bd24-1393d5309e76,True

Here, NR is the number of record and by the default nature of awk record is same as line. So if you do NR>1 it will tell awk to perform action inside {..} on the lines number greater than 1.

Or use sed, here replace end of line $ with True:

sed '2,$s/$/True/' file
id,budget
d4385ff7-247f-407a-97c6-366d8128c6c7,True
50548d0a-257c-44f5-b175-2e7efa53dc35,True
e15965cf-ffc1-40ae-94c4-b450ab190233,True
b9286b97-2575-4c98-bd24-1393d5309e76,True

Upvotes: 3

Related Questions