0

How can I extract a word that comes after a specific word in bash ? More precisely, I have a file which has a line which looks like this:

Demo.txt

    IN=../files/d
    out=../files/d
    dataload
    name

i want to read "d" from above line.

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

this code helping if line having "."

IN=../files/d.txt

so its printing "d"

here we have "d" without "." as end delimeter. So i want to read till end of line. i/p :

Demo.txt

IN=../files/d
    out=../files/d
    dataload
    name

output looking for:

d
d

code: in bash

Deepak
  • 27
  • 7

3 Answers3

0

This sed variant should work for you:

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

d
d

Minor change from earlier sed is that it doesn't match \. right after first capture group.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You could use GNU grep with PCRE :

grep -oP '/files/\K[^.]+' file

The -P flag makes grep use PCRE, the -o makes it display only the matched part rather than the full line, and the \K in the regex omits what precedes from the displayed matched part.

Alternatively if you don't have access to GNU grep, the following perl command will have the same effect :

perl -nle 'print $& if m{/files/\K[^.]+}' file

Sample run.

Aaron
  • 24,009
  • 2
  • 33
  • 57
  • @Deepak neither `-o` nor `-P` are POSIX-specified, I guess you must not be using GNU grep. In this case I don't think there are any `grep`-based solutions. I'll leave my answer in case others would use it. – Aaron Sep 03 '18 at 14:52
  • @Deepak would you happen to have `perl` available? According to [this answer](https://stackoverflow.com/a/16658690/1678362) I could easily rewrite the `grep -P` command into a `perl` one. – Aaron Sep 03 '18 at 14:54
  • @Deepak I've updated my answer to include a `perl` solution. Note that I haven't got any experience with `perl`, I just followed the linked answer's suggestions. I've added it to my sample run so I can attest it seems to work, but I can't tell if it's really good. – Aaron Sep 03 '18 at 15:01
  • If this (or anubhava's) answer has solved your problem, please accept it :) – Aaron Sep 03 '18 at 15:53
0

When you don't want to think about a single command solution, you can use

grep -Eo "/files/." Demo.txt | cut -d/ -f3
Walter A
  • 19,067
  • 2
  • 23
  • 43