How to use grep command in linux with []

Viewed 61

I want to use grep command to check if [200] after the space exist in this string

https://wwww.example.com/2000/file200.js [200]
https://wwww.example.com/2020/file201.js [404]

I tried to grep "[200]" and grep "\[200\]" but none of them worked.

I need to save the link too after checking with grep so for example it will be something like this

cat links.txt | grep "[200]" > output.txt

the output.txt should contain the links, not the status codes.

Edit: It works with echo but it doesn't work with cat or when I try to give the input from another command. The command should be like Command | grep "[200]" | cut -d' ' -f1 > New links

6 Answers

Looks like you're getting colored output using your command. You may use this grep:

some_command | grep '\[[^]]*200[^]]*]'

https://wwww.example.com/2000/file200.js [200]

RegEx Breakup:

  • \[: Match a [
  • [^]]*: Match 0 or of any characters that are not ]
  • 200: Match text 200
  • [^]]*: Match 0 or of any characters that are not ]
  • ]: Match a ]

Something like this?

-F, --fixed-strings PATTERNS are strings

grep -F '[^[[32m200^[[0m]' file | cut -d' ' -f1

Your example works perfectly for me with the escapes in

 echo "https://wwww.example.com/99/file99.js [200]" | grep "\[200\]"

Then if you just want the first part you can use awk which is like a mini programming language you can use in the terminal. Where print $1 just prints the characters before the first space

echo "https://wwww.example.com/99/file99.js [200]" | grep "\[200\]" | awk '{print $1}'

OUTPUT:

https://wwww.example.com/99/file99.js

Using sed:

sed -n 's/ \[200]$//p' links.txt > output.txt

Using sed

$ sed -En '/([^[]*) \[200]/s//\1/pwoutput.txt' input_file
https://wwww.example.com/2000/file200.js
$ cat output.txt
https://wwww.example.com/2000/file200.js
  • the whole line
nawk 'NF *= ($-_)~__' __=' [[]200[]]$' 
gawk 'NF *= ($NF)~__' __='[[]200[]]'
mawk 'NF*=/ [[]200[]]$/'   
https://wwww.example.com/2000/file200.js [200]
  • just the URL
gawk 'NF = !_<NF' OFS= FS=' [[]200[]]$'
                            # personally I prefer consistent approach
nawk 'NF = / [[]200[]]$/'   # when escaping "[" and "]" instead of
mawk 'NF = / \[200]$/'      # <—- this asymmetric but still POSIX-compliant one 
https://wwww.example.com/2000/file200.js
Related