5

Say I have a file like this:

foo bar foo bar foo bar foo bar something useful"foo bar foo bar"

Basically, I want to know how I can get the string something useful by itself, either saved to its own file or displayed as output alone.

There will always be the same number of characters (33) before something useful and there will always be " directly after it.

5 Answers 5

13

Try this:

cut -c 34- | cut -d '"' -f1

First cut removes the first 33 characters; second cut keeps only the part before the first ".

0
6

Here is GNU grep version using perl syntax:

grep -oP '.{32}\K[^"]*'

it greps first 32 characters, cuts it away with \K and prints the rest until first ".

3

In bash and parameter expansion expression

$ nline="${line%%\"*}" #strip everything from first " seen to the end
$ echo "${nline:32}"   #print everything from offset 32 to the end
2

A vim solution:

vim test.txt -c '%s/\v.{32}(.{-})".*/\1' -c 'w output.txt' -c 'q!'

Saves the result in output.txt, which obviously could be changed.

1

You can use sed to achieve your task

sed -e 's/^.\{32\}//;s/".*//' filename.txt

This removes the first 32 characters and removes everything after the first ".

These substitutions will occur on every line of the file. To apply this to a specific line, use this:

sed -e 'linenumber{s/^.\{32\}//;s/".*//;}' filename.txt

where linenumber is any number.

linenumber{          # on the linenumber-th line, do the following
 s/^.\{32\}//        #  remove the first 33 characters
 s/".*//             #  remove the first quote and everything following it
}
1
  • @TobySpeight Thanks for spotting my mistake, I always mix up // with line numbers.
    – user41805
    Aug 2, 2017 at 9:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .