codehitman
codehitman

Reputation: 1188

How to rename file extentions in fish in a for loop?

Here is the equivalent bash script that I am trying to convert to fish:

for j in *.md; do mv -v -- "$j" "${j%.md}.txt"; done

Here is what I tried:

for file in *.md
    mv -v -- "$file" "{{$file}%.md}.txt"
end

But it simply ends up renaming all of the files like so:

‘amazon.md’ -> ‘{{amazon.md}%.md}.txt’

How do I do this correctly?

Upvotes: 13

Views: 6513

Answers (4)

Anstro Pleuton
Anstro Pleuton

Reputation: 31

Another nice way to do this is with string replace command in fish as described in https://fishshell.com/docs/current/cmds/string-replace.html

for f in *.md; mv $f $(string replace ".md" ".txt" $f); end

Upvotes: 3

glenn jackman
glenn jackman

Reputation: 247062

To do this just with fish:

for j in *.md
    mv -v -- $j (string replace -r '\.md$' .txt $j)
end

Upvotes: 13

hek2mgl
hek2mgl

Reputation: 158150

The fish shell doesn't support parameter expansion operations like bash. The philosophy of the fish shell to let existing commands do the work instead of re-inventing the wheel. You can use sed for example:

for file in *.md
    mv "$file" (echo "$file" | sed '$s/\.md$/.txt/')
end

Upvotes: 4

codehitman
codehitman

Reputation: 1188

I found an alternative solution to this:

for file in *.md
    mv -v -- "$file" (basename $file .md).txt 
end

It works like a charm!

Upvotes: 17

Related Questions