Аналог less в windows

UNIX-based and windows system equivalent commands.

I will be adding many more commands.

NOTE: I’m mainly focusing on command prompt on windows.

UNIX

cat command


:: `cat` command is `type` on windows.
type file.txt

grep command


:: `grep` command is `findstr` (Command Prompt) on windows.
findstr "foo"

# `grep` command is `Select-String` (PowerShell) on windows.
Select-String "foo"

less command


:: `less` command is equivalent to `more` command on windows, but `less` is more powerful.
:: you can install `less` on windows, but `more` is on by default.
more

clear command


:: `clear` command is `cls` command on windows.
:: `clear` command works on PowerShell as well.
cls

ls command


:: `ls` command is `dir` command on windows.
:: `ls` command works on PowerShell as well.
dir

rm command


:: `rm` command is `del` command on windows.
:: `rm` command works on PowerShell as well.
del file.txt

touch command


:: `touch` command is `copy nul` or `type nul` command on windows.
type nul >> "file.txt"

:: Does not work on PowerShell.
copy nul "file.txt"

which command


:: `which` command is `where` on windows.
where git

Windows

type command


# `type` command is `cat` on UNIX.
cat file.txt

findstr command (Command Prompt) or Select-String command (PowerShell)


# `findstr` and `Select-String` command is grep on UNIX.
grep "foo"

more command


# `more` command is equivalent to `less` command on UNIX, but it's not as powerful.
# you can install `less` on windows.
less

cls command


# `cls` command is `clear` command on UNIX.
# `clear` command works on PowerShell as well.
clear

dir command


# `dir` command is `ls` command on UNIX.
ls

del command


# `del` command is `rm` command on UNIX.
rm file.txt

copy nul and type nul command


# `copy nul` or `type nul` command is `touch` command on UNIX.
touch file.txt

where command


# `where` command is `which` on UNIX.
which git

LESS Compiler

Compile less source and get CSS styles using our LESS Compiler. Beautify or minify CSS if necessary.

Best LESS Compiler Alternatives for Windows

Want a really good LESS Compiler alternative? Take a look at these popular alternatives if you’re hunting for software similar to LESS Compiler. Let’s take a quick peek at some comparison that highlight your device and platform.

Prepros

Free PersonalMacWindowsLinux

Compile Less, Sass, Scss, Stylus, Jade, Coffeescript, Haml and Markdown with live browser refresh. Prepros is a web design & development tool that does all the…

Features:

  • Developer Tools
  • Web Development

Koala

FreeOpen SourceMacWindowsLinux

Koala is a gui for Less, Sass, Compass and CoffeeScript. Koala can run in windows, mac, and linux. Features Multi-language Support: support for Less,Sass…

Scout-App

FreeOpen SourceMacWindowsLinuxnode-webkit

Scout-App is a cross-platform desktop app that delivers the power of Sass to the hands of web designers. Scout-app helps make your CSS workflow a snap by delivering…

Features:

  • Compiler
  • Drag n drop
  • Portable

Crunch!

FreemiumMacWindowsLinux

Write your LESS markup. Crunch it into a CSS file. Link the crunched CSS file in your HTML. CRUNCH allows you to organize your LESS/CSS styles into some well-organized…

SimpLESS

FreeMacWindows

SimpLESS is your easy-to-use LESS CSS compiler.

Features:

  • Compiler
  • Web Development

Upvote Comparison

Interest Trends

LESS Compiler Reviews

Add your reviews & share your experience when using LESS Compiler to the world. Your opinion will be useful to others who are looking for the best LESS Compiler alternatives.




Web-Based



Windows



Mac



Linux



Бесплатно



Открытый исходный код

56

С помощью VWO FullStack можно легко тестировать и внедрять сложные функции. Он обеспечивает адаптацию на стороне сервера для проведения различных экспериментов с глубокой сегментацией, гарантируя оптимальную производительность и согласованность дейс…

13

Генерация CSS-кода из sass-источника с помощью SASS Compiler. Украсить CSS, если это необходимо.

Koala

Бесплатно

Открытый исходный код

39

Коала это графический интерфейс для Less, Sass, Compass и CoffeeScript. Коала может работать в Windows, Mac и Linux.

LESS Compiler

28

LESS Compiler делает отформатированные стили CSS из меньшего количества источников.

LESS Compiler делает отформатированные стили CSS из меньшего количества источников.

LESS Compiler Платформы

Web-Based

LESS Compiler Обзор

Скомпилируйте меньше исходного кода и получите стили CSS, используя наш LESS Compiler. Украсьте или уменьшите CSS, если это необходимо.

Лучшие аналоги LESS Compiler

Поделитесь своим мнением о программном обеспечении, оставьте отзыв и помогите сделать его еще лучше!

LESS Compiler Категории

LESS Compiler Теги

less

compilers

css

There have been some interesting developments recently in the field of CSS pre-processors. CSS pre-processors work around the very limited syntax of CSS by allowing you to create your stylesheets using a more powerful, expressive syntax which then gets turned into plain CSS for consumption by all the main browsers. A couple of ones that I’ve come across are SASS and LESS. LESS is the one I’ve felt most comfortable with because it’s simply an augmentation of the CSS which allows you to incrementally introduce its syntax into your stylesheets.

For example LESS supports variables:

@brand_color: #4D926F;
#header {
   color: @brand_color;
}
h2 {
   color: @brand_color;
}

nested rules:

#header {
  color: red;
  a {
    font-weight: bold;
  }
}

…mixins, operations on colors and size, etc. Check out the  lesscss.org homepage for more.

LESS was originally a Ruby gem, but now also has implementations on ASP.NET (dotlesscss.org) and PHP. LESS has now (inevitably) been re-implemented in JavaScript by Alexis Sellier (github.com/cloudhead/less.js). As well as supporting pre-processing *.less files into *.css via the command-line, it can also be actually run live, directly in your browser!

<link rel="stylesheet/less" href="stylesheets/main.less" type="text/css" />
<script src="script/less-1.0.38.min.js"></script>

I’m not sure I’m quite ready to take the plunge running it live, in-browser on sites just yet, although maybe I shouldn’t be according to Dmitry Fadeyev:

Wouldn’t live processing lag? Not really. Two reasons for this. One: Less.js has been written from the ground up for great performance, so even browsers with poor JavaScript implementation should still run it very well (Less.js is about 40 times faster than the Ruby implementation—so suffice to say it’s a lot faster.). Two: On modern browsers that support HTML5, Less.js will cache the generated CSS on local storage, making subsequent page loads as fast as pure CSS.

Running on Windows

The command-line compiler lessc is targeted to *nix-based platforms and requires node.js which, the last time I checked, doesn’t run on Windows (UPDATE: it runs fine under Cygwin, there’s a nice simple standalone version here). But Windows has had the ability to run JavaScript directly since the 1990’s using Windows Script Host. So I took the latest distribution copy of less.js from GitHub at https://github.com/cloudhead/less.js/tree/master/dist/ and included it via a *.wsf file and stubbed/faked/implemented a few things like window, document and XMLHttpRequest that less.js assumes will be present (which are presumably provided by node.js?), and added a bit of command-line argument handling.

Download

Browse the code and download from GitHub: https://github.com/duncansmart/less.js-windows and feel free to fork it and send me pull requests!

Usage

To use it, invoke lessc.wsf via cscript.exe like so:

cscript //nologo lessc.wsf input.less [output.css] [-compress] 

I’ve also added a less.cmd shim which will simplify it to just:

lessc input.less [output.css] [-compress] 

If you don’t specify an output.css the result is written to standard output. The -compress option minifies the output. I’ll look into implementing the other command-line arguments supported by lessc in due course.

I’ve added a couple of test files, so you can see if it’s working like so:

C:codelessc-wsh>lessc test.less
/* Variables */
#header {
  color: #4d926f;
}
h2 {
  color: #4d926f;
}
/* Mixins */
#header {
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
}
...

Future

I may look into hooking this into Visual Studio’s T4 support so that the *.css files are generated as soon as you save the *.less files in Visual Studio. (UPDATE: See Phil Haack’s T4CSS that does this, instead using  the .NET port of LESS. Thanks to David De Sloovere for pointing this out.)

Update

Mark Lagendijk has created a nice little Windows GUI for the script. Check it out at http://winless.org.

Published

Время на прочтение8 мин

Количество просмотров19K

Типичный вопрос разработчиков под Windows: «Почему здесь до сих пор нет <ВСТАВЬТЕ ТУТ ЛЮБИМУЮ КОМАНДУ LINUX>?». Будь то мощное пролистывание less или привычные инструменты grep или sed, разработчики под Windows хотят получить лёгкий доступ к этим командам в повседневной работе.

Подсистема Windows для Linux (WSL) сделала огромный шаг вперёд в этом отношении. Она позволяет вызывать команды Linux из Windows, проксируя их через wsl.exe (например, wsl ls). Хотя это значительное улучшение, но такой вариант страдает от ряда недостатков.

  • Повсеместное добавление wsl утомительно и неестественно.
  • Пути Windows в аргументах не всегда срабатывают, потому что обратные слэши интерпретируются как escape-символы, а не разделители каталогов.
  • Пути Windows в аргументах не переводятся в соответствующую точку монтирования в WSL.
  • Не учитываются параметры по умолчанию в профилях WSL с алиасами и переменными окружения.
  • Не поддерживается завершение путей Linux.
  • Не поддерживается завершение команд.
  • Не поддерживается завершение аргументов.

В результате команды Linux воспринимаются под Windows как граждане второго сорта — и их сложнее использовать, чем родные команды. Чтобы уравнять их в правах, нужно решить перечисленные проблемы.

Оболочки функций PowerShell

C помощью оболочек функций PowerShell мы можем добавить автозавершение команд и устранить необходимость в префиксах wsl, транслируя пути Windows в пути WSL. Основные требования к оболочкам:

  • Для каждой команды Linux должна быть одна оболочка функции с тем же именем.
  • Оболочка должна распознавать пути Windows, переданные в качестве аргументов, и преобразовывать их в пути WSL.
  • Оболочка должна вызывать wsl с соответствующей командой Linux на любой вход конвейера и передавая любые аргументы командной строки, переданные функции.

Поскольку этот шаблон может быть применён к любой команде, мы можем абстрагировать определение этих оболочек и динамически генерировать их из списка команд для импорта.

# The commands to import.
$commands = "awk", "emacs", "grep", "head", "less", "ls", "man", "sed", "seq", "ssh", "tail", "vim"
 
# Register a function for each command.
$commands | ForEach-Object { Invoke-Expression @"
Remove-Alias $_ -Force -ErrorAction Ignore
function global:$_() {
    for (`$i = 0; `$i -lt `$args.Count; `$i++) {
        # If a path is absolute with a qualifier (e.g. C:), run it through wslpath to map it to the appropriate mount point.
        if (Split-Path `$args[`$i] -IsAbsolute -ErrorAction Ignore) {
            `$args[`$i] = Format-WslArgument (wsl.exe wslpath (`$args[`$i] -replace "\\", "/"))
        # If a path is relative, the current working directory will be translated to an appropriate mount point, so just format it.
        } elseif (Test-Path `$args[`$i] -ErrorAction Ignore) {
            `$args[`$i] = Format-WslArgument (`$args[`$i] -replace "\\", "/")
        }
    }
 
    if (`$input.MoveNext()) {
        `$input.Reset()
        `$input | wsl.exe $_ (`$args -split ' ')
    } else {
        wsl.exe $_ (`$args -split ' ')
    }
}
"@
}

Список $command определяет команды для импорта. Затем мы динамически генерируем обёртку функции для каждой из них, используя команду Invoke-Expression (сначала удалив любые алиасы, которые будут конфликтовать с функцией).

Функция перебирает аргументы командной строки, определяет пути Windows с помощью команд Split-Path и Test-Path, а затем преобразует эти пути в пути WSL. Мы запускаем пути через вспомогательную функцию Format-WslArgument, которую определим позже. Она экранирует специальные символы, такие как пробелы и скобки, которые в противном случае были бы неверно истолкованы.

Наконец, передаём wsl входные данные конвейера и любые аргументы командной строки.

С помощью таких обёрток можно вызывать любимые команды Linux более естественным способом, не добавляя префикс wsl и не беспокоясь о том, как преобразуются пути:

  • man bash
  • less -i $profile.CurrentUserAllHosts
  • ls -Al C:\Windows\ | less
  • grep -Ein error *.log
  • tail -f *.log

Здесь показан базовый набор команд, но вы можете создать оболочку для любой команды Linux, просто добавив её в список. Если вы добавите этот код в свой профиль PowerShell, эти команды будут доступны вам в каждом сеансе PowerShell, как и нативные команды!

Параметры по умолчанию

В Linux принято определять алиасы и/или переменные окружения в профилях (login profile), задавая параметры по умолчанию для часто используемых команд (например, alias ls=ls -AFh или export LESS=-i). Один из недостатков проксирования через неинтерактивную оболочку wsl.exe — то, что профили не загружаются, поэтому эти параметры по умолчанию недоступны (т. е. ls в WSL и wsl ls будут вести себя по-разному с алиасом, определённым выше).

PowerShell предоставляет $PSDefaultParameterValues, стандартный механизм для определения параметров по умолчанию, но только для командлетов и расширенных функций. Конечно, можно из наших оболочек сделать расширенные функции, но это вносит лишние осложнения (так, PowerShell соотносит частичные имена параметров (например, -a соотносится с -ArgumentList), которые будут конфликтовать с командами Linux, принимающими частичные имена в качестве аргументов), а синтаксис для определения значений по умолчанию будет не самым подходящим (для определения аргументов по умолчанию требуется имя параметра в ключе, а не только имя команды).

Однако с небольшим изменением наших оболочек мы можем внедрить модель, аналогичную $PSDefaultParameterValues, и включить параметры по умолчанию для команд Linux!

function global:$_() {
    …
 
    `$defaultArgs = ((`$WslDefaultParameterValues.$_ -split ' '), "")[`$WslDefaultParameterValues.Disabled -eq `$true]
    if (`$input.MoveNext()) {
        `$input.Reset()
        `$input | wsl.exe $_ `$defaultArgs (`$args -split ' ')
    } else {
        wsl.exe $_ `$defaultArgs (`$args -split ' ')
    }
}

Передавая $WslDefaultParameterValues в командную строку, мы отправляем параметры через wsl.exe. Ниже показано, как добавить инструкции в профиль PowerShell для настройки параметров по умолчанию. Теперь мы можем это сделать!

$WslDefaultParameterValues["grep"] = "-E"
$WslDefaultParameterValues["less"] = "-i"
$WslDefaultParameterValues["ls"] = "-AFh --group-directories-first"

Поскольку параметры моделируются после $PSDefaultParameterValues, вы можете легко их отключить на время, установив ключ "Disabled" в значение $true. Дополнительное преимущество отдельной хэш-таблицы в возможности отключить $WslDefaultParameterValues отдельно от $PSDefaultParameterValues.

Автозавершение аргументов

PowerShell позволяет регистрировать завершители аргументов с помощью команды Register-ArgumentCompleter. В Bash есть мощные программируемые средства для автозавершения. WSL позволяет вызывать bash из PowerShell. Если мы можем зарегистрировать завершители аргументов для наших оболочек функций PowerShell и вызвать bash для создания завершений, то получим полное автозавершение аргументов с той же точностью, что и в самом bash!

# Register an ArgumentCompleter that shims bash's programmable completion.
Register-ArgumentCompleter -CommandName $commands -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)
 
    # Map the command to the appropriate bash completion function.
    $F = switch ($commandAst.CommandElements[0].Value) {
        {$_ -in "awk", "grep", "head", "less", "ls", "sed", "seq", "tail"} {
            "_longopt"
            break
        }
 
        "man" {
            "_man"
            break
        }
 
        "ssh" {
            "_ssh"
            break
        }
 
        Default {
            "_minimal"
            break
        }
    }
 
    # Populate bash programmable completion variables.
    $COMP_LINE = "`"$commandAst`""
    $COMP_WORDS = "('$($commandAst.CommandElements.Extent.Text -join "' '")')" -replace "''", "'"
    for ($i = 1; $i -lt $commandAst.CommandElements.Count; $i++) {
        $extent = $commandAst.CommandElements[$i].Extent
        if ($cursorPosition -lt $extent.EndColumnNumber) {
            # The cursor is in the middle of a word to complete.
            $previousWord = $commandAst.CommandElements[$i - 1].Extent.Text
            $COMP_CWORD = $i
            break
        } elseif ($cursorPosition -eq $extent.EndColumnNumber) {
            # The cursor is immediately after the current word.
            $previousWord = $extent.Text
            $COMP_CWORD = $i + 1
            break
        } elseif ($cursorPosition -lt $extent.StartColumnNumber) {
            # The cursor is within whitespace between the previous and current words.
            $previousWord = $commandAst.CommandElements[$i - 1].Extent.Text
            $COMP_CWORD = $i
            break
        } elseif ($i -eq $commandAst.CommandElements.Count - 1 -and $cursorPosition -gt $extent.EndColumnNumber) {
            # The cursor is within whitespace at the end of the line.
            $previousWord = $extent.Text
            $COMP_CWORD = $i + 1
            break
        }
    }
 
    # Repopulate bash programmable completion variables for scenarios like '/mnt/c/Program Files'/<TAB> where <TAB> should continue completing the quoted path.
    $currentExtent = $commandAst.CommandElements[$COMP_CWORD].Extent
    $previousExtent = $commandAst.CommandElements[$COMP_CWORD - 1].Extent
    if ($currentExtent.Text -like "/*" -and $currentExtent.StartColumnNumber -eq $previousExtent.EndColumnNumber) {
        $COMP_LINE = $COMP_LINE -replace "$($previousExtent.Text)$($currentExtent.Text)", $wordToComplete
        $COMP_WORDS = $COMP_WORDS -replace "$($previousExtent.Text) '$($currentExtent.Text)'", $wordToComplete
        $previousWord = $commandAst.CommandElements[$COMP_CWORD - 2].Extent.Text
        $COMP_CWORD -= 1
    }
 
    # Build the command to pass to WSL.
    $command = $commandAst.CommandElements[0].Value
    $bashCompletion = ". /usr/share/bash-completion/bash_completion 2> /dev/null"
    $commandCompletion = ". /usr/share/bash-completion/completions/$command 2> /dev/null"
    $COMPINPUT = "COMP_LINE=$COMP_LINE; COMP_WORDS=$COMP_WORDS; COMP_CWORD=$COMP_CWORD; COMP_POINT=$cursorPosition"
    $COMPGEN = "bind `"set completion-ignore-case on`" 2> /dev/null; $F `"$command`" `"$wordToComplete`" `"$previousWord`" 2> /dev/null"
    $COMPREPLY = "IFS=`$'\n'; echo `"`${COMPREPLY[*]}`""
    $commandLine = "$bashCompletion; $commandCompletion; $COMPINPUT; $COMPGEN; $COMPREPLY" -split ' '
 
    # Invoke bash completion and return CompletionResults.
    $previousCompletionText = ""
    (wsl.exe $commandLine) -split '\n' |
    Sort-Object -Unique -CaseSensitive |
    ForEach-Object {
        if ($wordToComplete -match "(.*=).*") {
            $completionText = Format-WslArgument ($Matches[1] + $_) $true
            $listItemText = $_
        } else {
            $completionText = Format-WslArgument $_ $true
            $listItemText = $completionText
        }
 
        if ($completionText -eq $previousCompletionText) {
            # Differentiate completions that differ only by case otherwise PowerShell will view them as duplicate.
            $listItemText += ' '
        }
 
        $previousCompletionText = $completionText
        [System.Management.Automation.CompletionResult]::new($completionText, $listItemText, 'ParameterName', $completionText)
    }
}
 
# Helper function to escape characters in arguments passed to WSL that would otherwise be misinterpreted.
function global:Format-WslArgument([string]$arg, [bool]$interactive) {
    if ($interactive -and $arg.Contains(" ")) {
        return "'$arg'"
    } else {
        return ($arg -replace " ", "\ ") -replace "([()|])", ('\$1', '`$1')[$interactive]
    }
}

Код немного плотный без понимания некоторых внутренних функций bash, но в основном мы делаем следующее:

  • Регистрируем завершатель аргументов для всех наших обёрток функций, передавая список $commands в параметр -CommandName для Register-ArgumentCompleter.
  • Сопоставляем каждую команду с функцией оболочки, которую использует bash для автозавершения (для определения спецификаций автозавершения в bash используется $F, сокращение от complete -F <FUNCTION>).
  • Преобразуем аргументы PowerShell $wordToComplete, $commandAst и $cursorPosition в формат, ожидаемый функциями автозавершения bash в соответствии со спецификациями программируемого автозавершения bash.
  • Составляем командную строку для передачи в wsl.exe, который обеспечивает правильную настройку среды, вызывает соответствующую функцию автозавершения и выводит результаты с разбиением по строкам.
  • Затем вызываем wsl с командной строкой, разделяем выдачу разделителями строк и генерируем для каждой CompletionResults, сортируя их и экранируя символы, такие как пробелы и скобки, которые в противном случае были бы неверно истолкованы.

В итоге наши оболочки команд Linux будут использовать точно такое же автозавершение, как в bash! Например:

  • ssh -c <TAB> -J <TAB> -m <TAB> -O <TAB> -o <TAB> -Q <TAB> -w <TAB> -b <TAB>

Каждое автозавершение подоставляет значения, специфичные для предыдущего аргумента, считывая данные конфигурации, такие как известные хосты, из WSL!

<TAB> будет циклически перебирать параметры. <Ctrl + пробел> покажет все доступные опции.

Кроме того, поскольку теперь у нас работает автозавершение bash, вы можете автозавершать пути Linux непосредственно в PowerShell!

  • less /etc/<TAB>
  • ls /usr/share/<TAB>
  • vim ~/.bash<TAB>

В тех случаях, когда автозавершение bash не даёт никаких результатов, PowerShell возвращается к системе по умолчанию с путями Windows. Таким образом, вы на практике можете одновременно использовать и те, и другие пути на своё усмотрение.

Заключение

С помощью PowerShell и WSL мы можем интегрировать команды Linux в Windows как нативные приложения. Нет необходимости искать билды Win32 или утилиты Linux или прерывать рабочий процесс, переходя в Linux-шелл. Просто установите WSL, настройте профиль PowerShell и перечислите команды, которые хотите импортировать! Богатое автозавершение для параметров команд и путей к файлам Linux и Windows — это функциональность, которой сегодня нет даже в нативных командах Windows.

Полный исходный код, описанный выше, а также дополнительные рекомендации по его включению в рабочий процесс доступны здесь.

Какие команды Linux вы считаете наиболее полезными? Каких ещё привычных вещей не хватает при работе в Windows? Пишите в комментариях или на GitHub!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как отключить обновление office 2016 в windows 10
  • Windows xp не отображает компьютеры рабочей группы
  • Как зайти под администратором в windows server 2012
  • Установка rdp windows server 2016 без домена
  • Установка navi sailor 3000 на windows 10