2

I have a file like

foo.txt

xxx B=C     D: A
yyy F=H     D:A
zzz K=L     D:  A
fff M=H     D:/llll
kkk S=D     D: /kkkkk

this is what I try to get;

xxx B=C;     D: A           ;pass
yyy F=H;     D:A            ;pass
zzz K=L;     D:  A          ;pass
fff M=H;     D:/llll        ;try
kkk S=D;     D: /kkkkk/bb   ;try

The second part of line which starts with "D:",if starts with "/", it should be write "try" else it has to write "pass" end of the line for every line in it.

I can read file like this but there is spaces which is another problem

In addition after "D:" always starts with "A" or "/".

I tried while loop but I have not succeeded.

cat /tmp/foo.txt | cut -d ":" -f,2

Output

 A      (one empty space)
A       (none)
   A    (three empty space)
/llll   (none)
 /kkkkk/bb (two empty space)

This is a example what I have tried

while read -r line;
do 
if [[ $line ]]; then
          echo $line "try"
else
          echo $line "pass" 
fi
done < foo.txt
0

You can't write in the same file, I would recommend to create a new file and then rename it.

tmpFile="/tmp/foo2.txt.tmp"

cat /tmp/foo.txt | while read line; do
      isSlash=$(echo $line | cut -d ":" -f2 | awk '{print $1}' | grep -c ^"/")
      if (( $isSlash )); then
          echo "$line ;try" >> $tmpFile
      else 
          echo "$line ;pass" >> $tmpFile
      fi
done

mv $tmpFile /tmp/foo.txt
  • kkk S=D D: /kkkkk ;pass it writes pass beacause of the empty space before the "/" so can we add something that ignore the empty spaces? – 1010111100011 Nov 13 '18 at 17:51
  • I updated my answer, awk '{print $1}' will solve the issue with the empty space. – Javier Salas Nov 13 '18 at 18:02
1

You can use awk, which makes it very easy to accomplish what you want:

awk '!/D: *\//{print $0 " ;pass"; next} {print $0 " ;try"}' foo.txt

Output:

xxx B=C     D: A ;pass
yyy F=H     D:A ;pass
zzz K=L     D:  A ;pass
fff M=H     D:/llll ;try
kkk S=D     D: /kkkkk ;try

This basically matches every line not containing D: and / and appends ;pass to it, then skips to the next line. Otherwise it appends ;try to it.

0

sed OK?

$ sed '/D: *A/ s/$/\t;pass/; /D: *\// s/$/\t;try/' file
 xxx B=C     D: A   ;pass
 yyy F=H     D:A    ;pass
 zzz K=L     D:  A  ;pass
 fff M=H     D:/llll    ;try
 kkk S=D     D: /kkkkk  ;try
  • posixly: sed -e 's+D: */.*+&\t;try+ ; t' -e 's+$+\t;pass+' – Isaac Nov 13 '18 at 21:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.