Florian Schaal
Florian Schaal

Reputation: 2660

appending text to specific line in file bash

So I have a file that contains some lines of text separated by ','. I want to create a script that counts how much parts a line has and if the line contains 16 parts i want to add a new one. So far its working great. The only thing that is not working is appending the ',' at the end. See my example below:

Original file:

a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a
b,b,b,b,b,b
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a
b,b,b,b,b,b
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a

Expected result:

a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,xx
b,b,b,b,b,b
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a
b,b,b,b,b,b
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,xx

This is my code:

            while read p; do
                if [[ $p == "HEA"* ]]
                then
                    IFS=',' read -ra ADDR <<< "$p"
                    echo ${#ADDR[@]}
                    arrayCount=${#ADDR[@]}
                    if [ "${arrayCount}" -eq 16 ];
                    then
                        sed -i "/$p/ s/\$/,xx/g" $f 
                    fi
                fi
            done <$f

Result:

a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a
,xx
b,b,b,b,b,b
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a
b,b,b,b,b,b
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a
,xx

What im doing wrong? I'm sure its something small but i cant find it..

Upvotes: 2

Views: 3057

Answers (2)

user223217
user223217

Reputation: 11

For using sed answer should be in the following:

  1. Use ${line_number} s/..../..../ format - to target a specific line, you need to find out the line number first.
  2. Use the special char & to denote the matched string

The sed statement should look like the following:

sed -i "${line_number}s/.*/&xx/"

I would prefer to leave it to you to play around with it but if you would prefer i can give you a full working sample.

Upvotes: 1

anubhava
anubhava

Reputation: 786241

It can be done using awk:

awk -F, 'NF==16{$0 = $0 FS "xx"} 1' file
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,xx
b,b,b,b,b,b
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a
b,b,b,b,b,b
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,xx
  • -F, sets input field separator as comma
  • NF==16 is the condition that says execute block inside { and } if # of fields is 16
  • $0 = $0 FS "xx" appends xx at end of line
  • 1 is the default awk action that means print the output

Upvotes: 3

Related Questions