0

I made a script that uses du at some point, to show the space used into a directory. I want that to to be showed without the "/home/azarilh" in the string. I was trying to remove that with an example...

What i have:

5G /home/azarilh/folder/asd

What i want to get:

5G /folder/asd

I have tried (using echo instead of du as an example):

echo "5G /home/azarilh/folder/asd" | sed -e 's/\<\/home\/azarilh\>//g'

Would be better to get "~/folder/asd" instead of just removing "/home/azarilh". Doesn't need to be sed, i have tried with grep but with no success. I use grep to remove prefixes and it works.

echo "$string" | grep -oP "^$prefix\K.*"

Maybe it can be modified to work in this case?

Azarilh
  • 19
  • 4

3 Answers3

0

Could you please try following.

cho "5G /home/azarilh/folder/asd" | sed 's/\([^ ]* \)\/[^/]*\/[^/]*\(.*\)/\1\2/'

Detailed explanation: Using sed's group referencing capability here, which allows us to save matched regex into buffer memory with identification of 1,2 etc and so on. So when a regex is mentioned in between \(....\) and a match found in line then it will be saved into memory with reference of digit(which will depend upon its matched number, eg--> 1st matched regex reference number will be \1).


2nd solution: If you are ok with an awk solution it will be pretty simple(considering that you always have to print in output in same fashion).

echo "5G /home/azarilh/folder/asd" | awk -F'[ /]' '{print $1 OFS "/"$(NF-1)"/"$NF}'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0

This should do it:

echo "5G /home/azarilh/folder/asd" | sed -e 's+/home/azarilh+~+g'
# output: 5G ~/folder/asd

When you use sed you specify the pattern, what to change like s/from/to/g (to change "from" to "to"), but the / delimiter can be almost anything. So if you have / slashes in the string you want to modify, you can use something other than /, for example + as above.

You could also use on any output sed -e "s+${HOME}+~+ to replace your ${HOME} directory with ~.

But I think I should also mention, you can get a similar output to what you want by running du -hs ./* in your ${HOME} directory.

Emil Vatai
  • 2,298
  • 1
  • 18
  • 16
  • All three answers work, but using another character instead of the slash really is useful and simple to understand, hence, best answer. Thank you. Your du solution, tho', leaves a dot at the beginning of the directory, surely better than full path but substituting it with whatever i want is better. – Azarilh Nov 28 '19 at 06:11
0

This should work.

Remove the /home/azarilh part and replace it with ~.

I think that's what you desire, right?

$ echo "5G /home/azarilh/folder/asd" | sed -e 's/\/home\/azarilh/~/g'
5G ~/folder/asd
Siddharth
  • 321
  • 1
  • 5