Kino Perraz
Kino Perraz

Reputation: 9

Insert text into a filename in unix

Scenario:

#!/usr/bash/ksh
source_dir=/usr/idmp/bbp/

filename = "SURH00000321312"

insertText = `IDD`

I want the result like this SUIDDRH00000321312. How to add the insertText variable into a file name.

Upvotes: 0

Views: 201

Answers (2)

John1024
John1024

Reputation: 113924

This does what you ask:

$ new=${filename:0:2}$insertText${filename:2}
$ echo "$new"
SUIDDRH00000321312

This works by selecting substrings of the variable filename starting at an offset and continuing for a length via the shell form: ${parameter:offset:length}

Compatibility

Substring expansion works under ksh, bash, and zsh but not dash or tcsh.

Upvotes: 1

P....
P....

Reputation: 18391

Alternate way from sed:

new_name=$(echo SURH00000321312 |sed -r 's/(.)(.)/\1\2IDD/')
echo $new_name
SUIDDRH00000321312

Upvotes: 1

Related Questions