0

I am new to Shell scripting. I wanted to remove last 3 words from a file path including the file extension. Below is the example,

Input:

/tmp/errorlog_invest_CR12345_88_1:05:45.txt

Desired Output:

/tmp/errorlog_invest

Kindly help me to get the desired output. Thanks!

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Nirmal
  • 111
  • 1
  • 1
  • 12

1 Answers1

0

You need to look at this URL

You will find following solutions on this URL I am not able add comment so I am Just copy paste Ans

If you wanted to remove a certain NUMBER of path components, you should use cut with -d'/'. For example, if path=/home/dude/some/deepish/dir:

To remove the first two components:

$ echo $path | cut -d'/' -f4- some/deepish/dir

To remove the last three components (assuming no trailing slash):

$ echo $path | cut -d'/' -f-3 /home/dude

To KEEP the last three components (rev reverses the string):

$ echo $path | rev | cut -d'/' -f-3 | rev some/deepish/dir

Or, if you want to remove everything before a particular component, sed would work:

$ echo $path | sed 's/.*(some)/\1/g' some/deepish/dir

Or after a particular component:

$ echo $path | sed 's/(dude).*/\1/g' /home/dude

It's even easier if you don't want to keep the component you're specifying:

$ echo $path | sed 's/some.*//g' /home/dude/

And if you want to be consistent you can match the trailing slash too:

$ echo $path | sed 's//some.*//g' /home/dude

Of course, if you're matching several slashes, you should switch the sed delimiter:

$ echo $path | sed 's!/some.*!!g' /home/dude

Also, if you have filenames with / characters in them, you're totally boned.

Community
  • 1
  • 1
Rahul Bhawar
  • 450
  • 7
  • 17