Monday, April 29, 2024
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 827  / 2 Years ago, fri, december 31, 2021, 9:13:03

I have a file that has the name a_b-c-d-e-f.txt. I would like to take that current name and swap the dashes and underscores so that it becomes a-b_c_d_e_f.txt.


My intuition tells me to try rename or tr, but I'm having issues with this. Here is my current attempt


#!/bin/bash
for i in *.txt; do
[ -f "$i" ] || break
newFile=$(echo "$i" | tr '-' '_')
cp "$i" $newFile
done

With this, I end up with


a_b_c_d_e_f.txt

It's that part between a-b that should not be changing. Also, that dash is not necessarily always in that place in the filename. For example, it may look like


a-b-c_d-e-f.txt

Or any combination like this. I want them to flip not matter their place in the name.


More From » command-line

 Answers
2
for v in *.txt
do
newname=`echo $v | tr '_-' '-_'`
mv $v $newname
done

I found this to work. This was a combo of my post and Tony's response.


[#2349] Friday, December 31, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
intssive

Total Points: 493
Total Questions: 119
Total Answers: 101

Location: Liberia
Member since Mon, Feb 1, 2021
3 Years ago
;