halexh
halexh

Reputation: 3121

String Manipulation - Replace certain characters

A linux command I have outputs a list of files that look like this:

    folder/folder/folder/file_1
    folder_1/folder/folder/file2

I want to format this output so the following conditions are met:

The above would look like:

    folder_folder_folder___file_1
    folder__1_folder_folder___file2

If you could also explain your solution that would be helpful. Thanks!

Upvotes: 1

Views: 283

Answers (3)

Thor
Thor

Reputation: 47219

Here's one way you could do it with sed (tested with GNU sed):

<infile rev | sed -r 'h; s,_,__,g; G; s,[^/]+/([^\n]+)\n([^/]+/).*,\2\1,; :a; s,/,_,2; ta; s,/,___,' | rev

Output:

folder_folder_folder___file_1
folder__1_folder_folder___file2

rev makes it easier to parse, all it does is reverse the order of the characters on the line. I'll break down the sed script below:

h;                                  # save a copy of PS in HS, prepare to replace folder underscores
s,_,__,g;                           # replace folder underscores 
G;                                  # append HS to PS
s,[^/]+/([^\n]+)\n([^/]+/).*,\2\1,; # reorder into correct order
:a;
s,/,_,2;                            # replace most / with _, leave the first alone
ta;
s,/,___,                            # replace the first / with ___

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247192

an awk solution:

awk '
  BEGIN {FS="/";OFS="_"}
  {for (i=1; i<NF; i++) gsub("_","__",$i); $NF="__" $NF; print}
'

Upvotes: 1

kojiro
kojiro

Reputation: 77167

# Assume each line in a variable called $value
# Split the values up into dirname and basename
val_dir="${value%/*}"
val_base="${value##*/}"

# Replace underscores in dirname with two underscores
val_dir="${val_dir//_/__}"
# Replace slashes in dirname with single underscore
val_dir="${val_dir//\//_}"

# Re-join dirname and basename with three underscores
result="${val_dir}___${val_base}"

Upvotes: 2

Related Questions