mles
mles

Reputation: 3476

Extract first three characters of a string with words with bash, f.ex. with sed

From the string "Release Enterprise Production" I need to extract the first three characters of each word and put together the string "RelEntPro". I can put this in one line, but it's rather long:

export APP_NAME=""; 
for i in Release Enterprise Production; do 
   APP_NAME="$APP_NAME${i:0:3}"; 
done; 
echo $APP_NAME

Is there a more elegant way to do this with sed? or awk?

Upvotes: 1

Views: 577

Answers (2)

John Kugelman
John Kugelman

Reputation: 361889

Some tips to shorten your loop:

  • export is unnecessary.
  • += is a shortcut for concatenation.
  • ${i:0:3} can be shortened to ${i::3}.
  • Quotes aren't necessary on the right hand side of an assignment.

(It's best to avoid all uppercase variable names as they're reserved by the shell, so I changed APP_NAME to appName.)

appName=; for n in Release Enterprise Production; do appName+=${n::3}; done

Another way to do it is by using grep -o to match three characters at the beginning of each word and only print out the matching bits.

str="Release Enterprise Production"
egrep -o '\<...' <<< "$str" | tr -d '\n'

Or you can use Awk and loop over each field.

awk '{for(i=1;i<=NF;++i) printf "%s",substr($i,0,3); print ""}' <<< "$str"

Upvotes: 4

hamza tuna
hamza tuna

Reputation: 1497

You use cut to take chars:

echo 'Release Enterprise Production' | tr ' ' '\n' | cut -c-3 | echo $(cat) | sed 's/ //g'

outputs:

RelEntPro

Upvotes: 2

Related Questions