So i want to display the filename and the size of the file in MB using the "du" command in my bash script but it outputs the filepath for the file
I have used the command:
du -s -BM /home/user/test/test_file_check
But my output is:
0M /home/user/test/test_file_check
How do i get rid of the /home/user/test path from the output?
Would it be possible to use sed to remove the filepath?
Is there alternatively another command better suited for this?
CodePudding user response:
Since sed does greedy matching by default:
du -s -BM /home/user/test/test_file_check | sed 's|/.*/||'
sed is going to match the longest line that matches /.*/ (ie, greedy match) and then replace it with nothing (||). NOTE: since the data includes the / character we need a different script delimiter hence the use of | as the sed script delimiter
Simulating your du output:
$ echo '0M /home/user/test/test_file_check' | sed 's|/.*/||'
0M test_file_check
CodePudding user response:
A slightly tongue in cheek approach. This navigates to the directory and does the du in the local directory, then navigates back to the previous location.
cd /home/user/test/ && du -s -BM test_file_check && cd - > /dev/null || return
0M test_file_check
