Tanvir
Tanvir

Reputation: 174

How to add different characters at the end of text file

I have a text file with a lot of records. I want to add |column1|column2|column3 at the end of the first line and then for the rest of the lines I want to add |Munich|2017_01.003|City_stats

I have tried with sed -i 's/$/|column1|column2|column3/' filename.txt But this adds |column1|column2|column3 in all the lines.

Is there any easy approach to do this?

Upvotes: 0

Views: 34

Answers (2)

LeadingEdger
LeadingEdger

Reputation: 724

Here are two ways to produce the desired output, one using sed and the other using awk:

cat filename.txt
Line #1
Line #2
Line #3
Line #4

sed -e '1,1 s/$/|column1|column2|column3/' -e '2,$ s/$/|Munich|2017_01.003|City_stats/' filename.txt
Line #1|column1|column2|column3
Line #2|Munich|2017_01.003|City_stats
Line #3|Munich|2017_01.003|City_stats
Line #4|Munich|2017_01.003|City_stats

awk 'NR == 1 {print $0"|column1|column2|column3"}; NR > 1 {print $0"|Munich|2017_01.003|City_stats"}' filename.txt
Line #1|column1|column2|column3
Line #2|Munich|2017_01.003|City_stats
Line #3|Munich|2017_01.003|City_stats
Line #4|Munich|2017_01.003|City_stats

Upvotes: 0

halfbit
halfbit

Reputation: 3464

Use sed adresses to differentiate between header and data lines. For example (in bash)

echo $'a\nb\nc' | \
sed -e '1,1 s/$/|header/' -e '2,$ s/$/|data/'

outputs

a|header
b|data
c|data

Upvotes: 1

Related Questions