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.


Try this:

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

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

| improve this answer | |

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 ".

| improve this answer | |

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
| improve this answer | |

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.

| improve this answer | |

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
| improve this answer | |
  • @TobySpeight Thanks for spotting my mistake, I always mix up // with line numbers. – user41805 Aug 2 '17 at 9:13

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.