1
votes

I've a file like this:

 "text I don't know" command other "text" 
 "some" different text "type"

I need to obtain "text I don't know" and "some", with sed, awk or whatever bash tool, to be piped to another command.

Any hint?

3
Give an example from your file, a small one. Also, is this homework? - Priyank Bhatnagar

3 Answers

0
votes

This seems overly simple, which means you may be new to awk. Which is perfectly acceptable, or I misintreprted your question. I hope its the former.

The following should do what you ask. Setting the field separator to " -F\" (escape the " with ) and printing the second field, the first being to the left of ", or nothing. You can just put a pipe and the end of the line to do what you want.

awk -F\" '{print FS$2FS}' inputFile.txt

"text I don't know"
"some"

FS is Field Seperator

0
votes
sed 's/^\("[^"]*"\).*/\1/'

This deals with lines containing a simple double quoted field dropping any extra material. It passes through any lines not matching that unchanged.

If you want to drop non-matching lines, then:

sed -n '/^\("[^"]*"\).*/s//\1/p'

This doesn't print by default and prints when it finds a match.

If you have to deal with data fields such as:

"He said, ""It's horrid""" and he meant it!

then you have to work considerably harder. If your sed supports extended regular expressions or PCRE (Perl-Compatible Regular Expressions), you can do it. If not, use awk instead.

0
votes

Not sure if " should be part of output or not, assuming not. If I'm mistaken, it shouldn't be any problems for you to add it to the output (deliberately left sed out of the list below, since the answer from @Jonathan-Leffler is a very good one)

Not a perfect solution since " is output as the first character, but it is simple.

cut -d\" -f1-2 input

Solution using pure bash, see 5.1 Bourne Shell Variables for explanation of IFS

#!/bin/bash

IFS='"'

while read -ra LINE;
do
    echo ${LINE[1]}
done < input

Solution using awk, and the -F flag to change delimiter to "

$ awk -F\" '{print $2}' input

and finally one in perl. -a turns on autosplit mode – perl will automatically split input lines on whitespace into the @F array. -F is used in conjunction with -a, to choose the delimiter on which to split lines.

perl -F\" -lane 'print $F[1]' input