user2117336
user2117336

Reputation: 69

Manipulating the output string in bash shell

I have written a line that finds and returns the full path to a desired file. The output is as follows:

/home/ke/Desktop/b/o/r/files.txt:am.torrent
/home/ke/Desktop/y/u/n/u/s/files.txt:asd.torrent

I have to modify the output like this:

bor
yunus

How do I do that?

Thanks in advance.

Upvotes: 0

Views: 174

Answers (4)

piokuc
piokuc

Reputation: 26164

This should work for you:

your_script.sh | sed 's,.*Desktop,,' | sed 's,[^/]*$,,' | sed s,/,,g

or, even better:

your_script.sh | sed 's,.*Desktop,,;s,[^/]*$,,;s,/,,g'

Upvotes: 1

abasu
abasu

Reputation: 2524

it's not a nice/tidy solution, but bash parameter expansion is a powerful tool. So could not resist providing an example

[]l="/home/ke/Desktop/b/o/r/files.txt:am.torrent"
[]m=${l##*Desktop/}
[]n=${m%%/files.txt*}
[]k=${n//\//}
[]echo $m
b/o/r/files.txt:am.torrent
[]echo $n
b/o/r
[]echo $k
bor

You can see how nicely bash is replacing the variable step by step without using any external program (btw [] is PS1, prompt) There can be many more ways to do it. I got another one while writing the first

[]l="/home/ke/Desktop/b/o/r/files.txt:am.torrent"
[]m=${l/*Desktop\//}
[]n=${m/\/files.txt*/}
[]k=${n//\//}
[]echo $m
b/o/r/files.txt:am.torrent
[]echo $n
b/o/r
[]echo $k
bor

Try some more,

Upvotes: 0

Fredrik Pihl
Fredrik Pihl

Reputation: 45634

Id resort to awk:

BEGIN { FS="/" }

{
  for(i=1;i<NF;i++)
    if (length($i) == 1)
      a[NR]=a[NR]""$i
}
END {
  for (i in a)
    print a[i]
}

use it like this:

$ awk -f script.awk input
bor
yunus

or if you have your data in a variable:

$ awk -f script.awk <<< $data

Upvotes: 0

With sed. echo '/home/ke/Desktop/b/o/r/files.txt:am.torrent' | sed -e 's+/++g' -e 's/^.*Desktop//' -e 's/files.txt:.*$//'. This is a fairly trivial solution, and I'm sure there are better ones.

Upvotes: 0

Related Questions