Find the answer to your Linux question:
Results 1 to 2 of 2
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    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:
    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
    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.
    So in the example given above, it would be this line:
    Code:
    that is the second testline
    And the line right above it would be:
    Code:
    line above it 03
    I tried doing different kinds of for and while loops with sed etc. but can't get this working. Can someone please help?

    Thank you!

  2. #2
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •