Hi there,
I'm having some problem here with searching line. Lets say I got 1 text file which output will be:
A: Hi
B: Bye
C: GG
D: LOL
A: second
B: zzz
C: here
D: help
I will prompt user to input string that want to find and only can match with 1st line. So if user input "Hi", then, then it will display 2nd and 3rd line.
I can grep for the 1st line but I don't know how to make it if 1st line string match, then display 2nd and 3rd line. Hope all can understand what I mean
Sorry, what I mean was I want to match the A: field only. like if I input "here" to search for string, it will not work. But if I input "Hi" or "second", it will work because is same line with A:
I'm not sure if this will help, but if you can already grep the A line and only need it to also print out line B and C with the A line, you can add the -A option to grep. -A will print out however many lines you want below the string you grep. Here you would want to try "grep -A 2 Hi"
That will grep the "Hi" line and also print out the two lines below it.
# ./test.sh
Type search string:
Hi
A: Hi
B: Bye
C: GG
# ./test.sh
Type search string:
Bye
B: Bye
C: GG
D: LOL
# ./test.sh
Type search string:
second
A: second
B: zzz
C: here
# ./test.sh
Type search string:
zzz
B: zzz
C: here
D: help
#
i got tried your method before and found out is not what I want because I only want to find string inside the A: line only...and tukuyomi's code is work for me.
btw, based on the output of the file at 1st post, if I want to modify the third field only, can I use grep/awk/sed? lets say it will match the third field which is C: with the string I input. If match, then it can let me modify the GG or here to something else in C: field and save it.
I tried that before too but it doesn't get what I want.
Like this, I will prompt user to input the string inside the A: field.
if the string match with A: field then will prompt user to enter new string that need to replace for C: field.
I even tried sed but still won't work
hmm..i tried it but get error:
syntax error at line 73: `line3=$' unexpected
Like this, I will prompt user to input the string inside the A: field.
if the string match with A: field then will prompt user to enter new string that need to replace for C: field.
#!/bin/sh
read -p'A input: ' inputA
while read line; do
if [ "A: "${inputA} = "${line}" ]; then
read lineB; read lineC
match='true'
break
fi
done < 'file'
if [ ${match} = 'true' ]; then
read -p'input C: ' inputC
sed -i 's/'"${lineC}"'/C: '"${inputC}"'/' 'file'
fi
exit 0
Well, as far as I tested, it works for me.
If A: matches, then we read lineB and lineC, we set a variable match and we break the while loop
if match is true (A: = Hi or second), then we read inputC from the user and we replace the actual line in the file (make a backup in case it does not work as you want)