Insert text into a filename in unix

2019-09-06 02:22发布

问题:

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.

回答1:

Alternate way from sed:

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


回答2:

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.



标签: shell