- This topic has 1 reply, 1 voice, and was last updated 10 years, 1 month ago by .
Viewing 1 reply thread
Viewing 1 reply thread
- You must be logged in to reply to this topic.
› Forums › Basic skills › Programming › Shell scripting (in bash) › Simple string manipulations
Often, you need to modify a string (such as a filename or a path) in the shell. Here are some useful ways to do that.
The basename command strips prefixes and suffixes from strings like this:
$ basename path/to/some_file.txt some_file.txt $ basename some_file.txt some_file.txt $ basename some_file.txt .txt some_file
You might need to cut a string on a separator, keeping only some parts if it. There are lots of ways to do that. The built-in cut command is one way (and you can pass it files too, whereby it will perform the same operation to all lines). The pipe “|” sends the output of one process to the input of the next.
$ # -c cuts using character positions $ echo some_file.txt | cut -c6-9 file $ # -d cuts using the delimiter you specify $ echo some_file.txt | cut -d"_" -f1 some $ # and -f specifies which field(s) you want to keep $ echo some_file.txt | cut -d"_" -f2 file.txt $ echo a_long_file_name.txt | cut -d"_" -f2-4 long_file_name.txt
Some forums are only available if you are logged in. Searching will only return results from those forums if you log in.
This is the new version. Still under construction.Copyright © 2026 · Balance Child Theme on Genesis Framework · WordPress · Log in