Skip to content
Advertisement

How to auto insert a string in filename by bash?

I have the output file day by day:

linux-202105200900-foo.direct.tar.gz

The date and time string, ex: 202105200900 will change every day.

I need to manually rename these files to

linux-202105200900x86-foo.direct.tar.gz

( insert a short string x86 after date/time )

any bash script can help to do this?

Advertisement

Answer

If you’re always inserting the string “x86” at character #18 in the string, you may use that command:

var="linux-202105200900-foo.direct.tar.gz"
var2=${var:0:18}"x86"${var:18}
echo $var2

The 2nd line means: “assign to variable var2 the first 18 characters of var, followed by x86 followed by the rest of the variable var”

If you want to insert “x86” just before the last hyphen in the string, you may write it like this:

var="linux-202105200900-foo.direct.tar.gz"
var2=${var%-*}"x86-"${var##*-}
echo $var2

The 2nd line means: “assign to variable var2:

  • the content of the variable var after removing the shortest matching pattern “-*” at the end
  • the string “x86-“
  • the content of the variable var after removing the longest matching pattern “*-” at the beginning
Advertisement