Want to have a script to process screen prints as grep.
I can run it like: cat file.txt | my_script
Tried below script, it didn't print out anything.
#!/bin/bash
line=$@
echo $line
Want to have a script to process screen prints as grep.
I can run it like: cat file.txt | my_script
Tried below script, it didn't print out anything.
#!/bin/bash
line=$@
echo $line
You are trying to read from command line arguments ($@
) while you should be reading from stdin
.
Basically the pipe attaches the first command's stdout
to the second's stdin
.
A simple way how to do what you wanted in bash would be to use the read
built-in command, line by line as in the example.
#!/bin/bash
while read line
do
echo $line
done
Of course you can do whatever you want instead of echo.
cat
as the body of the script would be safer, if you just want to pass the output through. Your code would remove flanking whitespace, multiple whitespace characters between words, and it would potentially also expand filename globbing patterns if these were fed into the script. Additionally, echo
may interpret certain escape sequences, like \t
and \n
etc.
– Kusalananda
Jul 15 '21 at 09:54
Same idea as @glemco's answer but this version should be safe for special characters (excluding a NULL byte):
#!/bin/bash
while IFS= read -r line
do
printf '%s\n' "$line"
done
IFS=
is to prevent trimming the leading and trailing whitespace-r
is used to prevent backslash escapes to be processed"
around "$line"
are to prevent glob expansion, and to prevent replacing whitespace sequences with a single space
grep
purely as a shell script? Your script, if you invoke it like you show, does output something: an empty line. – Kusalananda Jul 15 '21 at 08:48read
to read fromstdin
. If you want to use the data in another command, which reads from stdin, you can simply call it. – ibuprofen Jul 15 '21 at 09:43cat /dev/stdin
orgrep -o '.' /dev/stdin
. Do not forget to specify the path to the script:./my_script
– nezabudka Jul 15 '21 at 09:58awk '/A/ { x=$1; (if x > N) {do something}}; /B/ { y=$1; if (y > M) {do something else}}'
(assuming that both x & y's values come from field 1 of the input). I suggest posting another question asking how to do what you want in awk or perl. The better you can describe what you want to do, with a representative sample of the input and desired output, the better answer you'll get (and it'll probably turn out to be a lot simpler & easier than you thought it would be). Partial code or pseudo-code is good, too. – cas Jul 27 '21 at 18:20if
. write it asif (x > 100)
, as in the /B/ example. – cas Jul 28 '21 at 03:23