How to touch a file and mkdir if needed in one line

前端 未结 8 991
抹茶落季
抹茶落季 2021-02-18 14:38

I need to touch a file with an absolute file name such as: /opt/test/test.txt, but I\'m not sure if there is /opt/test existed on the system. So the code should similar with thi

相关标签:
8条回答
  • 2021-02-18 14:39
    mkdir B && touch B/myfile.txt
    

    Alternatively, create a function:

       mkfile() { 
        mkdir -p $( dirname "$1") && touch "$1" 
       }
    

    Execute it with 1 arguments: filepath. Saying:

    mkfile B/C/D/myfile.txt
    

    would create the file myfile.txt in the directory B/C/D.

    0 讨论(0)
  • 2021-02-18 14:50

    In a shell script, you can simply do:

    mkdir -p /opt/test && touch /opt/test/test.txt
    

    mkdir -p will not fail (and won't do anything) if the directory already exists.

    In perl, use make_path from the File::Path module, then create the file however you want. make_path also doesn't do anything if the directory exists already, so no need to check yourself.

    0 讨论(0)
  • 2021-02-18 14:52

    I defined a touchp in my ~/.bash_aliases:

    function touchp() {
      /bin/mkdir -p "$(dirname "$1")/" && /usr/bin/touch "$1"
    }
    

    It silently creates the structure above the file if not present, and is perfectly safe to use when passed a single filename without any directory in front of it.

    0 讨论(0)
  • 2021-02-18 14:54

    Perl from command line,

    perl -MFile::Basename -MFile::Path=make_path -e'
      make_path(dirname($_)), open(F, ">>", $_) for pop;
    ' /opt/test/test.txt
    
    0 讨论(0)
  • 2021-02-18 14:59

    Bring Python to command line.

    i.e. Use pyp

     cat filepaths.txt | pyp "'mkdir -p '+s[0:-1]|s+'; touch '+o" | sh
    

    The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.

    0 讨论(0)
  • 2021-02-18 15:00

    I have this shell function in my .zshalias file:

    function touch-safe {
        for f in "$@"; do
          [ -d $f:h ] || mkdir -p $f:h && command touch $f
        done
    }
    alias touch=touch-safe
    

    If either the test or the mkdir command fail, no touch command is invoked.

    0 讨论(0)
提交回复
热议问题