I have a text file where every line is in a similar format to this:

%#&#%#    [Dinero]    / Money / 
!#@%$@    [Dia]     / Day /
$%&$^#@ [Perro]   / Dog / 

I am looking to extract the words inside the brackets, ie. Ola, Dinero, Perro, etc, and save it all to a new text file line by line. Essentially, I am looking to omit/delete/erase all words, letters, special characters, and anything else outside the brackets, including the brackets themselves.


with the help of awk,

$ awk -F'[][]' '{print $2}' < input

Using grep,

grep -oP '\[\K[^\]]+' input

\K means that use look around regex advanced feature. More precisely, it's a positive look-behind assertion

if you lack the -P option, you can do this with perl:

perl -lne '/\[\K[^\]]+/ and print $&' input

use -i option to edit file in place.

Or simply you can use cut as suggested by @juliepelletier,

cut -d"[" -f2 < input | cut -d"]" -f1
  • 3
    For the sake of simplicity, I was thinking of answering: cat input|cut -d\[ -f2|cut -d\] -f1 – Julie Pelletier Jul 4 '16 at 18:13
  • @juliepelletier yes, updated your suggestion in answer. Thanks – Rahul Jul 4 '16 at 18:21
  • 1
    You even golfed it nicely. – Julie Pelletier Jul 4 '16 at 18:22
  • 1
    huh, I've not actually used the \K flag. seems useful. Given the requirements, I'd have simply done grep -o -e '\[.*\]' file.txt | sed -e 's/\[//' -e 's/\]//' to find and extract all words with the brackets surrounding them and then strip away the brackets. And yes, that's the slightly verbose variant - could also be done more concisely with the same effect. It just better describes the flow I'd have put the data through. I keep meaning to pick up awk but I can never find the time. – VLAZ Jul 4 '16 at 19:16
  • I think you need <input, not > input – Matthew Finlay Jul 5 '16 at 0:29
sed 's/^.*\[//;s/\].*$//' /path/to/input > /path/to/output

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.