Reputation: 351
I am relatively new to shell scripting so apologies. I have found older questions which insert strings based on a string which appears in a line, but my lines are all of the same format.
I have a file in which I want to insert a string 'insert_text. below each line. I used vim to search for the line break and insert the string below in the following:
%s/\n/\r insert_text.\r/
The above works fine. However, I have 250 lines in my file and 12 specific lines for which I don't wish to insert the string below. I could search for each specific line and remove the string, but I would like to write a shell script that could automate it.
This is as close as I've got
#!/bin/bash
for line in {179, 170, 183, 104, 187, 172, 173, 171, 11, 7, 105, 3}
do
sed '\n/\r insert_text.\r/'
done
Obviously the above loop makes no sense, and the above code does the opposite of what I want, I want to insert the string into all the other lines.
Is there something similar to -v which would select all other lines in the for loop?
Upvotes: 3
Views: 367
Reputation: 98118
Using sed, b
jumps out, a
appends.
sed '179b;170b;183b;104b;187b;172b;173b;171b;11b;7b;105b;3b;ainsert_text' file
Upvotes: 1
Reputation: 52579
Using perl:
perl -pe 'BEGIN { %skip = map { $_ + 1 => 1 } 0, 179, 170, 183, 104, 187, 172, 173, 171, 11, 7, 105, 3 } print "\n" unless exists $skip{$.}' foo.txt
(The 0 in the list of lines to not print an extra newline after is important)
Upvotes: 0
Reputation: 786091
You can use this awk
command:
awk -v ln='179,170,183,104,187,172,173,171,11,7,105,3' '
ln !~ "(^|,)" NR "(,|$)"{$0 = $0 "\n insert_text."} 1' file
ln
!~
operator we ensure current line number doesn't match this comma delimited stringUpvotes: 2