user2686786
user2686786

Reputation: 19

Replacing a line with two new lines

I have a file named abc.csv which contains these 6 lines:

xxx,one
yyy,two
zzz,all
aaa,one
bbb,two
ccc,all

Now whenever all comes in a line that line should be replaced by both one and two, that is:

xxx,one
yyy,two
zzz,one
zzz,two
aaa,one 
bbb,two
ccc,one
ccc,two

Can someone help how to do this?

Upvotes: 2

Views: 98

Answers (2)

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45576

$ awk -F, -v OFS=, '/all/ { print $1, "one"; print $1, "two"; next }1' foo.input
xxx,one
yyy,two
zzz,one
zzz,two
aaa,one
bbb,two
ccc,one
ccc,two

If you want to stick to a shell-only solution:

while read line; do
    if [[ "${line}" = *all* ]]; then
        echo "${line%,*},one"
        echo "${line%,*},two"
    else
        echo "${line}"
    fi
done < foo.input

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

In sed:

sed '/,all$/{ s/,all$/,one/p; s/,one$/,two/; }'

When the line matches ,all at the end, first substitute all with one and print it; then substitute one with two and let the automatic print do the printing.

Upvotes: 0

Related Questions