Results 1 to 2 of 2
Hi All,
So I've been trying to do this for a while now with not much luck as I'm a newbie to bash scripting.
Example of file:
Code:
line above ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 09-06-2011 #1Just Joined!
- Join Date
- Feb 2006
- Posts
- 5
a little tricky.. adding comment but in specific case
Hi All,
So I've been trying to do this for a while now with not much luck as I'm a newbie to bash scripting.
Example of file:
What I want is to put comment (#) at the beginning of line that contains the string "second" and starts with "that" AND I also want to put a comment (#) on the line right above it.Code:line above it 01 this is a testline for a pattern line above it 02 this is the second testline line above it 03 that is the second testline line above it 04 this is the third testline line above it 05 that is the third testline
So in the example given above, it would be this line:
And the line right above it would be:Code:that is the second testline
I tried doing different kinds of for and while loops with sed etc. but can't get this working. Can someone please help?Code:line above it 03
Thank you!
- 09-08-2011 #2Trusted Penguin
- Join Date
- May 2011
- Posts
- 3,657
I'd do this with bash's built-in arrays. Assume your file contents are in a file named "test1.txt".
Code:#!/bin/bash file=test1.txt declare -i n declare -a lines n=0 while read line; do # echo Line $n: $line echo $line|grep -q '^that .*second' if [ $? -eq 0 ]; then lines[$n]="#${line}" lines[$(($n - 1))]="#${lines[$(($n - 1))]}" else lines[$n]="$line" fi let n+=1 done < $file #echo -e "Number of lines: ${#lines[*]}\n" for (( i=0; i<${#lines[*]}; i++ )); do echo "${lines[$i]}" done


Reply With Quote
